/*
 * strcat_s.c - Safe string concatenation with bounds checking
 */

#include "bounds_check.h"
#include "bounds_check_internal.h"
#include <string.h>

int strcat_s(char *dest, size_t dest_size, const char *src) {
    if (!is_valid_buffer(dest, dest_size) || src == NULL) {
        return BOUNDS_CHECK_INVALID_PARAM;
    }

    /* Find end of destination string */
    size_t dest_len = 0;
    while (dest[dest_len] != '\0' && dest_len < dest_size) {
        dest_len++;
    }

    if (dest_len >= dest_size) {
        /* Destination not null-terminated within bounds */
        return BOUNDS_CHECK_INVALID_PARAM;
    }

    /* Calculate remaining space */
    size_t remaining = dest_size - dest_len - 1; /* -1 for null terminator */

    /* Copy source string */
    size_t src_len = 0;
    while (src[src_len] != '\0' && src_len < remaining) {
        dest[dest_len + src_len] = src[src_len];
        src_len++;
    }

    if (src[src_len] != '\0') {
        /* Source string too long */
        dest[dest_len] = '\0';
        return BOUNDS_CHECK_BUFFER_TOO_SMALL;
    }

    /* Null terminate */
    dest[dest_len + src_len] = '\0';

    return BOUNDS_CHECK_SUCCESS;
}